import {Button, Modal, message, Select} from 'antd'
import React, {useRef, useState, useEffect} from 'react'
import {
	ActionType,
	ProColumns,
	EditableProTable,
} from '@ant-design/pro-components'
import {PlusOutlined} from '@ant-design/icons'
import type {ColumnsType} from 'antd/es/table'
import CustomTable from '@/components/Table'
import {getGoodsList} from '@/service/storage/outDepot'
import styles from './index.less'

type DataSourceType = {
	id: React.Key
	goodsCode?: string
	goodsName?: string
	goodsQuantity?: string
	goodsType?: string
	inOutType?: string
}

interface DataType {
	id: string
	goodsCode: string
	goodsArchivesName: string
	archivesStatus: string
	company: string
	largeClassify: string
	middleClassify: string
	createTime: string
}
type propsType = {
	data: any
	edit: boolean
	materialList: any[]
	dictData: any
	outWarehouse: any
	setMaterialList: React.Dispatch<React.SetStateAction<any[]>>
	setDataList: React.Dispatch<any>
}

const materialTable = (props: propsType) => {
	const {
		data,
		edit,
		setDataList,
		outWarehouse,
		materialList,
		setMaterialList,
		dictData,
	} = props
	const actionRef = useRef<ActionType>()
	const [total, setTotal] = useState()
	const [loading, setLoading] = useState(false)
	const [params, setParams] = useState({
		current: 1,
		size: 10,
	})
	const [editableKeys, setEditableRowKeys] = useState<React.Key[]>([])
	const [isModalOpen, setIsModalOpen] = useState(false)
	const [checkData, setCheckData] = useState<any>()
	useEffect(() => {
		if (edit) {
			setEditableRowKeys(data.map((item: {id: any}) => item.id))
		}
	}, [data])
	useEffect(() => {
		if (isModalOpen) {
			setCheckData(undefined)
		}
	}, [isModalOpen])

	// 获取物料档案列表
	const getData = () => {
		setLoading(true)
		const query = {
			...params,
			inWarehouse: outWarehouse?.id,
			goodsType: '2',
		}
		getGoodsList(query)
			.then((res: any) => {
				if (res?.data) {
					setMaterialList(res?.data?.records)
					setTotal(res?.data?.total)
					setLoading(false)
				}
			})
			.catch((err) => {
				setMaterialList([])
				message.error(err)
				setLoading(false)
			})
	}
	useEffect(() => {
		if (outWarehouse) {
			getData()
		}
	}, [params, outWarehouse])

	const columns: ProColumns<DataSourceType>[] = [
		{
			title: '代码',
			dataIndex: 'goodsCode',
			readonly: true,
		},
		{
			title: '名称',
			dataIndex: 'goodsName',
			readonly: true,
		},
		{
			title: '出库数量',
			dataIndex: 'goodsQuantity',
			formItemProps: {
				rules: [
					{
						required: true,
						whitespace: true,
						message: '此项是必填项',
					},
					{
						message: '请输入正确的数量，且数量不能为零',
						pattern: /^([1-9][0-9]*)$/,
					},
				],
			},
		},
		{
			title: '备注',
			dataIndex: 'remark',
		},
		{
			title: '操作',
			valueType: 'option',
			hideInTable: !edit,
			width: 250,
			render: () => null,
		},
	]
	const modalColumns: ColumnsType<DataType> = [
		{
			title: '代码',
			dataIndex: 'goodsCode',
			align: 'center',
			width: 180,
		},
		{
			title: '名称',
			dataIndex: 'goodsName',
			align: 'center',
			width: 120,
		},
		{
			title: '库存数量',
			dataIndex: 'goodsQuantity',
			align: 'center',
			width: 100,
		},
		{
			title: '大分类',
			dataIndex: 'largeClassify',
			align: 'center',
			width: 100,
			render: (text) => (
				<Select
					value={text}
					disabled
					allowClear
					fieldNames={{value: 'dictKey', label: 'dictValue'}}
					options={dictData?.storage_large_classify}
				/>
			),
		},
		{
			title: '中分类',
			dataIndex: 'middleClassify',
			align: 'center',
			width: 100,
			render: (text) => (
				<Select
					value={text}
					disabled
					allowClear
					fieldNames={{value: 'dictKey', label: 'dictValue'}}
					options={dictData?.storage_middle_classify}
				/>
			),
		},
		{
			title: '单位',
			dataIndex: 'company',
			align: 'center',
			width: 100,
			render: (text) => (
				<Select
					value={text}
					disabled
					allowClear
					fieldNames={{value: 'dictKey', label: 'dictValue'}}
					options={dictData?.Company}
				/>
			),
		},
	]
	const handleOk = () => {
		if (checkData) {
			const newData = [...data]
			newData.push({
				id: Date.now(),
				total: checkData?.goodsQuantity,
				goodsCode: checkData?.goodsCode,
				goodsName: checkData?.goodsName,
				goodsId: checkData?.goodsId,
				goodsType: '2',
				inOutType: '0',
			})
			setDataList(newData)
			setEditableRowKeys(newData.map((item) => item.id))
			setIsModalOpen(false)
		} else {
			message.warning('请选择物料')
		}
	}

	return (
		<div className={styles.MaterialTable}>
			<div className={styles.title}>
				物料信息
				{edit ? (
					<Button
						icon={<PlusOutlined />}
						type="primary"
						ghost
						size="small"
						style={{marginLeft: '24px'}}
						onClick={() => {
							if (outWarehouse) {
								setIsModalOpen(true)
							} else {
								message.warning('请先选择出库仓')
							}
						}}>
						添加物料
					</Button>
				) : (
					''
				)}
			</div>
			<EditableProTable<DataSourceType>
				columns={columns}
				rowKey="id"
				scroll={{
					x: 700,
				}}
				actionRef={actionRef}
				value={data}
				recordCreatorProps={false}
				editable={{
					type: 'multiple',
					editableKeys,
					actionRender: (row, config, defaultDoms) => [
						defaultDoms.delete,
					],
					onValuesChange: (record, recordList) => {
						setDataList(recordList)
					},
					onChange: setEditableRowKeys,
				}}
			/>
			<Modal
				width={700}
				title="添加物料"
				open={isModalOpen}
				onOk={handleOk}
				destroyOnClose
				onCancel={() => setIsModalOpen(false)}>
				<CustomTable
					type="radio"
					params={params}
					columns={modalColumns}
					total={total}
					pagination
					callback={(pagination: any) => {
						setParams(pagination)
					}}
					kid="goodsCode"
					getCheckboxProps={{
						getCheckboxProps: (record: any) => ({
							disabled: data.find(
								(item: {goodsCode: any}) =>
									item?.goodsCode === record?.goodsCode,
							),
						}),
					}}
					showRowSelection
					selectCallback={(keys: any, selectData: any) => {
						setCheckData(selectData[0])
					}}
					loading={loading}
					dataSource={materialList}
				/>
			</Modal>
		</div>
	)
}

export default materialTable
